<?php

namespace app\api\controller;

use app\admin\model\Price;
use app\admin\model\Goods;
use app\common\controller\Api;
use app\common\model\MoneyLog;
use think\Config;
use think\Db;
use think\Exception;

/**
 * 提现接口
 */
class Withdraw extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];
    public function _initialize(){
        parent::_initialize();
    }
    /**
     * 提现记录
     */
    public function index()
    {
        $limit = request()->param('limit',10);
        $userid = $this->auth->id;
        $model = new \app\admin\model\Withdraw();
        $list = $model
            ->where(['user_id'=>$userid])
            ->order('id', 'desc')
            ->paginate($limit);
        $this->success('请求成功',[
            'list' => $list
        ]);
    }

    /**
     * 余额记录
     */
    public function list()
    {
        $limit = request()->param('limit',10);
        $userid = $this->auth->id;
        $model = new MoneyLog();
        $list = $model
            ->where(['user_id'=>$userid])
            ->order('id', 'desc')
            ->paginate($limit);
        $this->success('请求成功',[
            'list' => $list
        ]);
    }

    /**
     * 提现申请
     */
    public function apply()
    {
        $user = $this->auth->getUser();
        $money = request()->param('money');
        $withdraw_type = request()->param('withdraw_type','wechat');//wechat=微信零钱,alipay=支付宝账户
        $withdraw_info = request()->param('info');
        $cache = cache('withdraw'.$user->id);
        if($cache) $this->error('请不要重复点击');
        cache('withdraw'.$user->id,$user->id,5);
        if($money <= 0) $this->error('请输入正确的金额');
        if(!$withdraw_info) $this->error('请输入提现信息');
        if($money > $user->money) $this->error('提现金额不能大于余额');
        Db::startTrans();
        try {
            \app\admin\model\Withdraw::create([
                'user_id' => $user->id,
                'amount' => $money,
                'withdraw_sn' => 'tx'.time().rand(100,999),
                'withdraw_type' => $withdraw_type,
                'withdraw_info' => $withdraw_info,
                'status' => 0,
            ]);
            \app\common\model\User::money(-$money,$user->id,'提现申请');
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('提现申请已提交');
    }
}
